package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"monthtest5th/cache"
	"monthtest5th/model"
	"strconv"
	"time"
)

func MerAdd(c *gin.Context) {
	address := c.PostForm("address")
	status := c.PostForm("status")
	if address == "" || status == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "请将信息填写完整",
		})
		return
	}
	data := model.Merhouse{
		Address: address,
		Status:  status,
	}
	if err := model.DB.Create(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func OrderAdd(c *gin.Context) {
	mid, _ := strconv.Atoi(c.PostForm("mid"))
	price, _ := strconv.Atoi(c.PostForm("price"))
	employee := c.PostForm("employee")
	if employee == "" || price == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "仓库信息不可为空",
		})
		return
	}
	data := model.Order{
		Mid:      mid,
		Price:    price,
		Employee: employee,
	}
	if err := model.DB.Create(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var data []model.MerOrder
	redis_key := "order_page_" + strconv.Itoa(page)
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		model.DB.Table("orders").
			Select("orders.id as Oid",
				"orders.price as Price",
				"orders.employee as Employee",
				"merhouses.address as Address",
				"merhouses.status as Status").
			Joins("left join merhouses on orders.mid = merhouses.id").
			Offset(offset).
			Limit(size).
			Find(&data)
		jsonData, _ := json.Marshal(&data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &data)
	}
	var total int64
	model.DB.Table("orders").Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  data,
		"total": total,
	})
}
func OrderDetail(c *gin.Context) {
	oid, _ := strconv.Atoi(c.Query("oid"))
	var data model.MerOrder
	redis_key := "order_" + strconv.Itoa(oid)
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		model.DB.Table("orders").
			Select("orders.id as Oid",
				"orders.price as Price",
				"orders.employee as Employee",
				"merhouses.address as Address",
				"merhouses.status as Status").
			Joins("left join merhouses on orders.mid = merhouses.id").
			Where("orders.id = ?", oid).
			Limit(1).
			Find(&data)
		jsonData, _ := json.Marshal(&data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &data)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": data,
	})
}
